package com.wyp168.gulimall.ware.service.impl;

import com.wyp168.common.constant.WareConstant;
import com.wyp168.gulimall.ware.entity.PurchaseDetailEntity;
import com.wyp168.gulimall.ware.service.PurchaseDetailService;
import com.wyp168.gulimall.ware.service.WareSkuService;
import com.wyp168.gulimall.ware.vo.MergeVO;
import com.wyp168.gulimall.ware.vo.PurchaseDetailDoneVO;
import com.wyp168.gulimall.ware.vo.PurchaseDoneVO;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyp168.common.utils.PageUtils;
import com.wyp168.common.utils.Query;

import com.wyp168.gulimall.ware.dao.PurchaseDao;
import com.wyp168.gulimall.ware.entity.PurchaseEntity;
import com.wyp168.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status" ,0).or().eq("status", 1)
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void autoMergePurchase(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (Objects.isNull(purchaseId)) {   //新建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());    //设置默认采购单的状态
            baseMapper.insert(purchaseEntity);

            purchaseId = purchaseEntity.getId();
        }
        List<Long> items = mergeVO.getItems();

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
    }

    @Override
    public void received(List<Long> ids) {
        //确认当前采购单是新建或者是已分配状态
        List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        purchaseEntities = purchaseEntities.stream().filter(o -> o.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                o.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    return item;
                })
                .collect(Collectors.toList());

        //改变采购单的状态
        this.updateBatchById(purchaseEntities);
        //改变采购需求的状态
        purchaseEntities.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetailsStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        Long id = purchaseDoneVO.getId();
        Integer count = baseMapper.selectCount(new QueryWrapper<PurchaseEntity>().eq("id", id));
        if (count == 0) {
            throw new RuntimeException("采购单id对应的采购项为空，请确认采购单id后重试");
        }
        //改变采购项状态
        Boolean flag = true;
        List<PurchaseDetailDoneVO> items = purchaseDoneVO.getItems();
        List<PurchaseDetailEntity> updateItems = new ArrayList<>();

        List<Long> purchaseDetailIds = items.stream().map(PurchaseDetailDoneVO::getItemId).collect(Collectors.toList());
        //封装成采购项和仓库id映射关系map
        Map<String, PurchaseDetailEntity> detailIdAndWareIdMap = purchaseDetailService.listByIds(purchaseDetailIds).stream().collect(Collectors.toMap(purchaseDetailEntity -> purchaseDetailEntity.getId().toString(), purchaseDetailEntity -> purchaseDetailEntity));

        for (PurchaseDetailDoneVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailsStatusEnum.FAIL.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.FINISH.getCode());
                //将成功采购的物品信息进行入库
                wareSkuService.addStock(item.getItemId(), detailIdAndWareIdMap.get(item.getItemId().toString()).getWareId(), detailIdAndWareIdMap.get(item.getItemId().toString()).getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updateItems.add(purchaseDetailEntity);
        }
        //批量更新
        purchaseDetailService.updateBatchById(updateItems);
        //改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.ERROR.getCode());
        this.updateById(purchaseEntity);
    }

}